<template>
  <div class="leaderboard-view">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="trophy-icon trophy-1">🏆</div>
      <div class="trophy-icon trophy-2">🥇</div>
      <div class="trophy-icon trophy-3">🥈</div>
      <div class="trophy-icon trophy-4">🥉</div>
    </div>
    
    <div class="container">
      <!-- 页面头部 -->
      <header class="page-header">
        <div class="header-content">
          <router-link to="/" class="back-btn">
            <i class="icon-arrow-left"></i>
            <span>返回</span>
          </router-link>
          <div class="title-section">
            <h1>排行榜</h1>
            <p>挑战最高分，成为跑酷之王！</p>
          </div>
        </div>
      </header>
      
      <!-- 时间筛选标签 -->
      <div class="filter-section">
        <div class="filter-tabs">
          <button 
            v-for="tab in tabs"
            :key="tab.id"
            class="filter-tab"
            :class="{ active: activeTab === tab.id }"
            @click="setActiveTab(tab.id)"
          >
            <i :class="tab.icon"></i>
            <span>{{ tab.name }}</span>
          </button>
        </div>
      </div>
      
      <div class="leaderboard-content">
        <div v-if="isLoading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载排行榜数据...</p>
        </div>
        
        <div v-else-if="currentScores.length === 0" class="empty-state">
          <div class="empty-icon">🏆</div>
          <h3>暂无记录</h3>
          <p>开始游戏创造你的第一个记录吧！</p>
          <router-link to="/game" class="btn btn-primary">
            开始游戏
          </router-link>
        </div>
        
        <div v-else class="scores-list">
          <div class="list-header">
            <div class="rank-col">排名</div>
            <div class="player-col">玩家</div>
            <div class="score-col">分数</div>
            <div class="date-col">日期</div>
          </div>
          
          <div 
            v-for="(score, index) in currentScores"
            :key="score.id"
            class="score-item"
            :class="{ 
              'top-score': index === 0,
              'personal-best': score.isPersonalBest 
            }"
          >
            <div class="rank-col">
              <div class="rank-badge" :class="getRankClass(index + 1)">
                {{ index + 1 }}
              </div>
            </div>
            <div class="player-col">
              <div class="player-info">
                <div class="player-avatar">
                  {{ score.playerName.charAt(0).toUpperCase() }}
                </div>
                <div class="player-details">
                  <div class="player-name">{{ score.playerName }}</div>
                  <div class="player-character">{{ score.characterName }}</div>
                </div>
              </div>
            </div>
            <div class="score-col">
              <div class="score-value">{{ formatScore(score.score) }}</div>
              <div class="score-details">
                <span>距离: {{ score.distance }}m</span>
                <span>时间: {{ formatTime(score.playTime) }}</span>
              </div>
            </div>
            <div class="date-col">
              <div class="date-value">{{ formatDate(score.date) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="personal-stats">
        <h3>个人统计</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">{{ personalStats.bestScore }}</div>
            <div class="stat-label">最高分数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ personalStats.totalGames }}</div>
            <div class="stat-label">游戏次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ personalStats.totalDistance }}m</div>
            <div class="stat-label">总距离</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ formatTime(personalStats.totalPlayTime) }}</div>
            <div class="stat-label">总游戏时间</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
// import { useGameStore } from '@/stores/gameStore' // 暂时注释掉，后续可能需要用到

/**
 * 排行榜视图组件
 * 显示游戏分数排行榜和个人统计信息
 * @component
 */

interface ScoreRecord {
  id: string
  playerName: string
  characterName: string
  score: number
  distance: number
  playTime: number
  date: Date
  isPersonalBest: boolean
}

interface PersonalStats {
  bestScore: number
  totalGames: number
  totalDistance: number
  totalPlayTime: number
}

interface Tab {
  id: string
  name: string
  icon: string
}

// const gameStore = useGameStore() // 暂时注释掉，后续可能需要用到

// 响应式数据
const isLoading = ref(false)
const activeTab = ref('all')

// 标签页配置
const tabs: Tab[] = [
  { id: 'all', name: '全部', icon: 'icon-all' },
  { id: 'today', name: '今日', icon: 'icon-today' },
  { id: 'week', name: '本周', icon: 'icon-week' },
  { id: 'month', name: '本月', icon: 'icon-month' }
]

// 模拟分数数据
const allScores = ref<ScoreRecord[]>([
  {
    id: '1',
    playerName: '玩家1',
    characterName: '跑步者',
    score: 15420,
    distance: 2840,
    playTime: 180,
    date: new Date('2024-01-15'),
    isPersonalBest: true
  },
  {
    id: '2',
    playerName: '玩家2',
    characterName: '疾风者',
    score: 12350,
    distance: 2100,
    playTime: 150,
    date: new Date('2024-01-14'),
    isPersonalBest: false
  },
  {
    id: '3',
    playerName: '玩家3',
    characterName: '跳跃者',
    score: 11200,
    distance: 1950,
    playTime: 140,
    date: new Date('2024-01-13'),
    isPersonalBest: false
  },
  {
    id: '4',
    playerName: '玩家4',
    characterName: '坦克',
    score: 9800,
    distance: 1800,
    playTime: 160,
    date: new Date('2024-01-12'),
    isPersonalBest: false
  },
  {
    id: '5',
    playerName: '玩家5',
    characterName: '跑步者',
    score: 8500,
    distance: 1600,
    playTime: 120,
    date: new Date('2024-01-11'),
    isPersonalBest: false
  }
])

// 个人统计数据
const personalStats = ref<PersonalStats>({
  bestScore: 15420,
  totalGames: 25,
  totalDistance: 45000,
  totalPlayTime: 3600
})

// 计算属性
const currentScores = computed(() => {
  const now = new Date()
  const scores = allScores.value

  switch (activeTab.value) {
    case 'today':
      return scores.filter(score => {
        const scoreDate = new Date(score.date)
        return scoreDate.toDateString() === now.toDateString()
      })
    case 'week':
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      return scores.filter(score => new Date(score.date) >= weekAgo)
    case 'month':
      const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate())
      return scores.filter(score => new Date(score.date) >= monthAgo)
    default:
      return scores
  }
})

/**
 * 设置活动标签页
 * @param tabId - 标签页ID
 */
const setActiveTab = (tabId: string): void => {
  activeTab.value = tabId
}

/**
 * 获取排名样式类
 * @param rank - 排名
 * @returns 样式类名
 */
const getRankClass = (rank: number): string => {
  if (rank === 1) return 'gold'
  if (rank === 2) return 'silver'
  if (rank === 3) return 'bronze'
  return ''
}

/**
 * 格式化分数
 * @param score - 分数
 * @returns 格式化后的分数字符串
 */
const formatScore = (score: number): string => {
  return score.toLocaleString()
}

/**
 * 格式化时间
 * @param seconds - 秒数
 * @returns 格式化后的时间字符串
 */
const formatTime = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

/**
 * 格式化日期
 * @param date - 日期对象
 * @returns 格式化后的日期字符串
 */
const formatDate = (date: Date): string => {
  return new Intl.DateTimeFormat('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }).format(new Date(date))
}

/**
 * 加载排行榜数据
 */
const loadLeaderboardData = async (): Promise<void> => {
  try {
    isLoading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该从游戏存储或API加载真实数据
    // const scores = await gameStore.getLeaderboardScores()
    // allScores.value = scores
    
    console.log('排行榜数据加载完成')
  } catch (error) {
    console.error('加载排行榜数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  loadLeaderboardData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/responsive.scss';

.leaderboard-view {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  margin: 0;
  overflow: hidden;
  z-index: 1000;
  
  @include mobile-all {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100vw;
    height: 100vh;
    height: -webkit-fill-available;
    padding: env(safe-area-inset-top, 1rem) env(safe-area-inset-right, 1rem) env(safe-area-inset-bottom, 1rem) env(safe-area-inset-left, 1rem);
    margin: 0;
  }

  // 背景装饰
  .background-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: 1;

    .trophy-icon {
      position: absolute;
      font-size: 3rem;
      opacity: 0.1;
      animation: trophyFloat 8s ease-in-out infinite;

      &.trophy-1 {
        top: 10%;
        left: 5%;
        animation-delay: 0s;
      }

      &.trophy-2 {
        top: 20%;
        right: 10%;
        animation-delay: 2s;
      }

      &.trophy-3 {
        bottom: 30%;
        left: 15%;
        animation-delay: 4s;
      }

      &.trophy-4 {
        bottom: 15%;
        right: 5%;
        animation-delay: 6s;
      }
    }
  }

  .container {
    position: relative;
    z-index: 10;
    width: 100%;
    height: 100%;
    max-width: none;
    margin: 0;
    padding: 2rem;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    
    @include mobile-all {
      padding: 1rem;
      max-width: none;
      width: 100%;
      height: 100%;
    }
    
    @include mobile-small {
      padding: 0.5rem;
    }
  }

  // 页面头部
  .page-header {
    margin-bottom: 3rem;
    
    @include mobile-all {
      margin-bottom: 2rem;
    }

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      
      @include mobile-all {
        flex-direction: column;
        gap: 1.5rem;
        text-align: center;
      }

      .back-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        background: rgba(255, 255, 255, 0.15);
        backdrop-filter: blur(10px);
        color: white;
        text-decoration: none;
        border-radius: $border-radius-lg;
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;
        font-weight: 500;
        
        @include mobile-all {
          align-self: flex-start;
          padding: 0.625rem 1.25rem;
        }
        
        @include touch-device {
          min-height: 44px;
          -webkit-tap-highlight-color: transparent;
          
          &:active {
            background: rgba(255, 255, 255, 0.25);
            transform: scale(0.98);
          }
        }

        @include non-touch-device {
          &:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
          }
        }

        i {
          font-size: 1.1rem;
        }
      }

      .title-section {
        text-align: right;
        
        @include mobile-all {
          text-align: center;
        }

        h1 {
          color: white;
          font-size: 3rem;
          font-weight: 900;
          margin-bottom: 0.5rem;
          text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.4);
          letter-spacing: -1px;
          
          @include mobile-all {
            font-size: 2.5rem;
          }
          
          @include mobile-small {
            font-size: 2rem;
          }
        }

        p {
          color: rgba(255, 255, 255, 0.9);
          font-size: 1.1rem;
          margin: 0;
          font-weight: 300;
          
          @include mobile-all {
            font-size: 1rem;
          }
          
          @include mobile-small {
            font-size: 0.9rem;
          }
        }
      }
    }
  }

  // 筛选标签
  .filter-section {
    margin-bottom: 2rem;
    
    @include mobile-all {
      margin-bottom: 1.5rem;
    }

    .filter-tabs {
      display: flex;
      gap: 0.5rem;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      padding: 0.5rem;
      border-radius: $border-radius-xl;
      border: 1px solid rgba(255, 255, 255, 0.2);
      
      @include mobile-all {
        flex-wrap: wrap;
        gap: 0.25rem;
      }

      .filter-tab {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        padding: 0.75rem 1rem;
        border: none;
        background: transparent;
        color: rgba(255, 255, 255, 0.7);
        border-radius: $border-radius-lg;
        cursor: pointer;
        transition: all 0.3s ease;
        font-weight: 500;
        
        @include mobile-all {
          padding: 0.625rem 0.75rem;
          font-size: 0.9rem;
        }
        
        @include mobile-small {
          flex-direction: column;
          gap: 0.25rem;
          padding: 0.5rem;
          font-size: 0.8rem;
        }
        
        @include touch-device {
          min-height: 44px;
          -webkit-tap-highlight-color: transparent;
          
          &:active {
            transform: scale(0.98);
          }
        }

        @include non-touch-device {
          &:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
          }
        }

        &.active {
          background: white;
          color: $primary-color;
          font-weight: 600;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        i {
          font-size: 1.1rem;
          
          @include mobile-small {
            font-size: 1rem;
          }
        }
      }
    }
  }

  .leaderboard-content {
    background: white;
    border-radius: $border-radius-lg;
    overflow: hidden;
    margin-bottom: 2rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .loading-state,
    .empty-state {
      padding: 3rem;
      text-align: center;

      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid rgba($primary-color, 0.3);
        border-top: 4px solid $primary-color;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 1rem;
      }

      .empty-icon {
        font-size: 4rem;
        margin-bottom: 1rem;
      }

      h3 {
        color: $text-color;
        margin-bottom: 0.5rem;
      }

      p {
        color: lighten($text-color, 20%);
        margin-bottom: 2rem;
      }

      .btn {
        padding: 0.75rem 2rem;
        background-color: $primary-color;
        color: white;
        text-decoration: none;
        border-radius: $border-radius-md;
        transition: $transition-normal;

        &:hover {
          background-color: darken($primary-color, 10%);
          transform: translateY(-2px);
        }
      }
    }

    .scores-list {
      .list-header {
        display: grid;
        grid-template-columns: 80px 1fr 200px 120px;
        gap: 1rem;
        padding: 1rem 1.5rem;
        background: lighten($secondary-color, 40%);
        font-weight: 600;
        color: $text-color;
        font-size: 0.9rem;
      }

      .score-item {
        display: grid;
        grid-template-columns: 80px 1fr 200px 120px;
        gap: 1rem;
        padding: 1rem 1.5rem;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        transition: $transition-normal;

        &:hover {
          background: rgba($primary-color, 0.05);
        }

        &.top-score {
          background: linear-gradient(90deg, rgba(255, 215, 0, 0.1), transparent);
        }

        &.personal-best {
          background: linear-gradient(90deg, rgba($primary-color, 0.1), transparent);
        }

        .rank-col {
          display: flex;
          align-items: center;

          .rank-badge {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 0.9rem;
            background: $secondary-color;
            color: white;

            &.gold {
              background: linear-gradient(135deg, #ffd700, #ffed4e);
              color: #b8860b;
            }

            &.silver {
              background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
              color: #696969;
            }

            &.bronze {
              background: linear-gradient(135deg, #cd7f32, #daa520);
              color: #8b4513;
            }
          }
        }

        .player-col {
          display: flex;
          align-items: center;

          .player-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;

            .player-avatar {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              background: $primary-color;
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: bold;
            }

            .player-details {
              .player-name {
                font-weight: 600;
                color: $text-color;
              }

              .player-character {
                font-size: 0.8rem;
                color: lighten($text-color, 20%);
              }
            }
          }
        }

        .score-col {
          display: flex;
          flex-direction: column;
          justify-content: center;

          .score-value {
            font-size: 1.2rem;
            font-weight: bold;
            color: $primary-color;
          }

          .score-details {
            display: flex;
            gap: 1rem;
            font-size: 0.8rem;
            color: lighten($text-color, 20%);
          }
        }

        .date-col {
          display: flex;
          align-items: center;
          justify-content: center;

          .date-value {
            font-size: 0.9rem;
            color: lighten($text-color, 20%);
          }
        }
      }
    }
  }

  .personal-stats {
    background: rgba(255, 255, 255, 0.95);
    padding: 2rem;
    border-radius: $border-radius-lg;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    h3 {
      color: $text-color;
      margin-bottom: 1.5rem;
      text-align: center;
      font-size: 1.5rem;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1.5rem;

      .stat-item {
        text-align: center;
        padding: 1rem;
        background: rgba($primary-color, 0.05);
        border-radius: $border-radius-md;

        .stat-value {
          font-size: 2rem;
          font-weight: bold;
          color: $primary-color;
          margin-bottom: 0.5rem;
        }

        .stat-label {
          color: lighten($text-color, 20%);
          font-size: 0.9rem;
        }
      }
    }
  }
}

// 动画定义
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes trophyFloat {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.1;
  }
  50% {
    transform: translateY(-15px) rotate(5deg);
    opacity: 0.2;
  }
}

// 图标样式
.icon-arrow-left::before { content: '←'; }
.icon-all::before { content: '📊'; }
.icon-today::before { content: '📅'; }
.icon-week::before { content: '📈'; }
.icon-month::before { content: '🗓️'; }

// 响应式设计优化
@include mobile-all {
  .leaderboard-view {
    .leaderboard-content {
      .scores-list {
        .list-header,
        .score-item {
          grid-template-columns: 50px 1fr 120px;
          gap: 0.5rem;
          padding: 0.75rem 1rem;
          
          .date-col {
            display: none;
          }
          
          .score-col {
            .score-details {
              flex-direction: column;
              gap: 0.25rem;
              
              span {
                font-size: 0.7rem;
              }
            }
          }
        }
      }
    }

    .personal-stats {
      padding: 1.5rem;
      
      .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
        
        .stat-item {
          padding: 0.75rem;
          
          .stat-value {
            font-size: 1.5rem;
          }
          
          .stat-label {
            font-size: 0.8rem;
          }
        }
      }
    }
  }
}

@include mobile-small {
  .leaderboard-view {
    .leaderboard-content {
      .scores-list {
        .list-header,
        .score-item {
          grid-template-columns: 40px 1fr 100px;
          
          .rank-col .rank-badge {
            width: 28px;
            height: 28px;
            font-size: 0.8rem;
          }
          
          .player-col .player-info {
            gap: 0.5rem;
            
            .player-avatar {
              width: 32px;
              height: 32px;
              font-size: 0.8rem;
            }
            
            .player-details {
              .player-name {
                font-size: 0.9rem;
              }
              
              .player-character {
                font-size: 0.7rem;
              }
            }
          }
          
          .score-col {
            .score-value {
              font-size: 1rem;
            }
          }
        }
      }
    }

    .personal-stats {
      .stats-grid {
        grid-template-columns: 1fr;
        
        .stat-item {
          .stat-value {
            font-size: 1.3rem;
          }
        }
      }
    }
  }
}

// 横屏模式优化
@include landscape {
  @include mobile-all {
    .leaderboard-view {
      .filter-section .filter-tabs {
        .filter-tab {
          flex-direction: row;
          gap: 0.5rem;
          padding: 0.5rem 0.75rem;
        }
      }
      
      .personal-stats .stats-grid {
        grid-template-columns: repeat(4, 1fr);
        
        .stat-item {
          .stat-value {
            font-size: 1.2rem;
          }
          
          .stat-label {
            font-size: 0.75rem;
          }
        }
      }
    }
  }
}
</style>